<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 产品评论模型
 * @author www.dingwei.cn
 */

class MerchantCommentModel extends MY_Model{
	
	public $tbComment = 'merchant_comment';
	public $tbMerchant = 'merchant';
	public $tbConsumer = 'consumer';
	public $tbProduct = 'product';
	public $tbOrder = 'consumer_order';
    public $tbShop = 'merchant_shop';
	
	function __construct(){
		parent::__construct();
	}

    /**
     * 保存评论
     * @param array     $data       数据
     * @param int       $id         评论id
     * @param bool      $isBatch    true：批量添加
     * @return bool|int
     * @author zyl
     */
    public function save($data,$id = 0, $isBatch = false){
        if ($id){
            if ($isBatch){
                return $this->updateBatch($this->tbComment, $data, 'id');
            }else{
                $this->db->where('id',$id);
                $query = $this->update($this->tbComment, $data);
                return $query === false ? false : true;
            }
        }else{
            if ($isBatch){
                return $this->insertBatch($this->tbComment, $data);
            }else{
                return $this->insert($this->tbComment, $data);
            }
        }
    }

    /**
     * 统计商户的平均分
     * @param $merchantId
     * @return float
     */
	public function totalCommentScore($merchantId){
		$this->db
		->select('avg(score) as avg_score')
		->where('merchant_id',$merchantId);
		$tA = $this->getOne($this->tbComment);
		return round(empty($tA['avg_score'])?5.0:$tA['avg_score'],2);
	}

    /**
     * 统计商户的平均分
     * @param $merchantId
     * @return float
     */
	public function totalCommentServiceScore($merchantId){
		$this->db
		->select('avg(service_score) as service_score')
		->where('merchant_id',$merchantId);
		$tA = $this->getOne($this->tbComment);
		return round(empty($tA['service_score'])?5.0:$tA['service_score'],2);
	}

    /**
     * 获取总平均分
     * @param $merchantId
     * @return float
     */
	public function totalScore($merchantId){
		$service = $this->totalCommentServiceScore($merchantId);
		$product = $this->totalCommentScore($merchantId);
		$score = round(($service + $product) / 2,1);
		return $score;
	}

    /**
     * @param int $id                   评论id
     * @param int $orderId              产品id
     * @param int $orderProductId       产品订单id
     * @param int $merchantId           商户id  @author khj
     * @return array
     * @author zyl
     */
	public function getInfo($id = 0,$orderId = 0,$orderProductId = 0, $merchantId = 0){
		
		if ( ! $id && ! $orderId && ! $orderProductId){
			return array();
		}
		
		if ($id){
			$this->db->where('id',$id);
		}
		if ($orderId){
			$this->db->where('order_id',$orderId);
		}
		if ($orderProductId){
			$this->db->where('order_product_id',$orderProductId);
		}

        if ($merchantId){
            $this->db->where('merchant_id', $merchantId);
        }

		$this->db->select('id,order_id,order_product_id,score,imgs,content');
		$tA = $this->getOne($this->tbComment);
		if (!empty($tA['imgs'])) {
            $img = json_decode($tA['imgs'], true);
            $imgArr = array();
            foreach ($img as $k => $v) {
                $imgArr[] = getImage($v, 'og');
            }
            $tA['imgs'] = $imgArr;
        }
		return $tA;
	}

    /**
     * 获取评论列表
     * @param int $merchantId       商家id
     * @param int $productId
     * @param int $page
     * @param int $type             类型 1全部 2好评 3差评 评分（1 2 差评 3 4 中评  5好评）
     * @return array
     * @author zyl
     */
	public function appGetCommentList($merchantId, $productId = 0, $page = 1, $type = 0){


		$this->db
		->select('id,consumer_id,score,content,imgs,reply,admin_reply,order_id,order_product_id,addtime')
		->where('merchant_id',$merchantId);
		
		if ($productId){
			$this->db->where('product_id',$productId);
		}

		if($type == 2){
            $this->db->where('score', 5);
        }

        if($type == 3){
            $this->db->where_in('score', array(1,2));
        }
		$this->db->order_by('addtime desc');
		$tA = $this->appPage($this->tbComment, $page , true);
	
		$tOrderProductIds = array(); 	//订单商品ids
		$tConsumerIds = array(); 		//用户ids
		
		/**
		 * 获取ids
		 */
		foreach ($tA['list'] as $k=>$v){
			//获取订单产品id
			if ( ! in_array($v['order_product_id'], $tOrderProductIds)){
				$tOrderProductIds[] = $v['order_product_id'];
			}
			//获取用户id
			if ( ! in_array($v['consumer_id'], $tConsumerIds)){
				$tConsumerIds[] = $v['consumer_id'];
			}
			
		}
		
		/**
		 * 获取商户信息
		 */
		get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$tMerchant = $this->mMerchant->getShopInfo($merchantId);
	
		/**
		 * 获取订单产品
		 */
		$tOProduct = array();
		if ($tOrderProductIds){
			get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
			$tOProduct = $this->mOrder->getOrderProductInfoByIds($tOrderProductIds);
		}

		/**
		 * 获取用户信息
		 */
		$tConsumer = array();
		if ($tConsumerIds){
			get_instance()->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
			$tConsumer = $this->mConsumer->getInfoByIds($tConsumerIds);
		}
		
		/**
		 * 处理数据
		 */
		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['desc'] = '';
			$tA['list'][$k]['name'] = '';
			$tA['list'][$k]['headurl'] = '';
			
			//评论图片
			$tImgs = json_decode($v['imgs'],true);
            $imgs = array();
			if ($tImgs){
				foreach ($tImgs as $kk=>$vv){
                    $imgs[] = getImage($vv,'og');
				}
			}
            $tA['list'][$k]['imgs'] = $imgs;

			$tA['list'][$k]['content'] = $v['content']; //处理内容
			
			if (isset($tOProduct[$v['order_product_id']])){
				$tA['list'][$k]['desc'] = $tOProduct[$v['order_product_id']]['property']?$tOProduct[$v['order_product_id']]['property']:'';
				$tA['list'][$k]['goods_name'] = $tOProduct[$v['order_product_id']]['name'];
			}
			
			if (isset($tConsumer[$v['consumer_id']])){
				$tA['list'][$k]['name'] = $tConsumer[$v['consumer_id']]['nickname'];
				$tA['list'][$k]['headurl'] = $tConsumer[$v['consumer_id']]['portrait']['xs'];
			}
			
			$tA['list'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
		}

        //店铺标签
        get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $tags = $this->mSetting->get('merchant_comment_tags');
        $tags = json_decode($tags);
        $tagsData = array();
        foreach ($tags as $k=>$v){
            $count = $this->mComment->getCommentTagsNumber($merchantId, $v);
            $tagsData[] = array('tags' => $v,'count' => $count);
        }

		//数据
		$service = $this->totalCommentServiceScore($merchantId);
		$product = $this->totalCommentScore($merchantId);
		$tData = array(
            'total_score'=>$this->totalScore($merchantId),
            'service'=>round($service,1),// 服务评分
            'product'=>round($product,1),// 产品评分
            'total_comment'=>(string)$tA['total'],//总评价 死数据
            'desc'=>$tagsData,
		);
		
		$tData['list'] = $tA['list'];
		return $tData;
	}

    /**
     * 根据订单id获取评论列表
     * @param int $orderId      订单id
     * @return array
     */
	public function getCommentListByOrderId($orderId = 0){
        if (!$orderId){
            return array();
        }
        $this->db->select('id,order_id,order_product_id,score')
            ->where(array('order_id' => $orderId));
        $tA = $this->getAll($this->tbComment);
        $data = array();
        if (!empty($tA)) {
            foreach ($tA as $k => $v) {
                $data[$v['order_product_id']] = $v;
            }
        }
        unset($tA);
        return $data;
    }

	/**
	 * 删除评论
	 * @param integer $id 评论id
     * @param int $consumerId
	 * @return array|boolean
	 * @author zyl
	 */
	public function removeComment($id,$consumerId = 0){
		if ( ! $id){
			return array();
		}
		$this->db->where('id',$id);
		if ($consumerId){
			$this->db->where('consumer_id',$consumerId);
		}
		$query = $this->delete($this->tbComment);
		return $query === false ? FALSE : TRUE;
	}

    /**
     * 获取店铺评分
     * @param $merchantId
     * @param bool $mini
     * @return array/string
     * @author khj
     */
	public function getStoreCommentScore($merchantId, $mini = false){
	    if(!$merchantId)return array();
        //今日
        $start = strtotime(date('Y-m-d'));
        $end = $start + 86400;

        $this->db->where('merchant_id', $merchantId);
        if($mini){
            $this->db->select('sum(score)/COUNT(merchant_id) as avg,sum(service_score)/COUNT(merchant_id) as service_avg');
        }
        $this->db->select('sum(score)/COUNT(merchant_id) as avg,
                            sum(service_score)/COUNT(merchant_id) as service_avg,
	                        count(if(score = 1, id, null)) as oneStar,
	                        count(if(score = 2, id, null)) as twoStar,count(if(score = 3, id, null)) as threeStar,
	                        count(if(score = 4, id, null)) as fourStar,count(if(score = 5, id, null)) as fiveStar,
	                        count(if(addtime >= '.$start.' and addtime < '.$end.', id, null)) as todayTotal,
	                        count(if(score in (1,2) and addtime >= '.$start.' and addtime < '.$end.', id, null)) as badTotal,
	                        count(if(score = 5 and addtime >= '.$start.' and addtime < '.$end.', id, null)) as goodTotal');

	    return $this->getOne($this->tbComment);
    }

    public function getCommentTagsNumber($merchantId, $tag){
        if(!$merchantId)return array();
        $this->db->where('merchant_id', $merchantId)
                 ->like('tags', ','.$tag.',');
        $count = $this->count($this->tbComment);
        return $count;
    }
	
	/////////////////////////////////////////////////
	//+----------------------------------------------
	//|	后台方法
	//+----------------------------------------------

    /**
     * 后台获取列表信息
     * @param int $merchantId
     * @param int $productId
     * @param array $ci
     * @return array
     */
	public function adminGetList($merchantId = 0, $productId = 0, $ci = array()){
		$name = trim(get('name'));
        $nickname = trim(get('m_name'));
        $score = trim(get('score'));
        $cName = trim(get('c_name'));
        $sendDateFrom = strtotime(trim(get('send_date_from')));
        $sendDateTo = strtotime(trim(get('send_date_to')));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($merchantId){
            $this->db->where(array('co.merchant_id' => $merchantId));
        }
        if ($productId){
            $this->db->where(array('co.product_id' => $productId));
        }
        if(!empty($ci)){
            $this->db->where_in('s.county',$ci);
        }
		if ($name){
			$this->db->where('p.name',$name);
		}
		if ($nickname){
			$this->db->like('s.shop_name',$nickname);
		}
		if ($score){
			$this->db->like('co.score',$score);
		}
		if ($cName){
			$this->db->like('c.nickname',$cName);
		}
        if($sendDateFrom){
            $this->db->where('co.addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('co.addtime <', strtotime('+1day', $sendDateTo));
        }

        if ($iSortCol_0 == 3){
            $this->db->order_by('co.score', $sSortDir_0);
        }else if ($iSortCol_0 == 7){
            $this->db->order_by('co.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('co.addtime desc');
        }
		
		$this->db->select('co.id,co.product_id,co.consumer_id,co.merchant_id,co.score,co.content,
						co.reply,co.imgs,co.addtime,c.nickname as c_name,s.shop_name as m_name,p.name,co.admin_reply,o.code')
		->join($this->tbConsumer.' c','co.consumer_id = c.id','left')//消费者
		->join($this->tbMerchant.' m','co.merchant_id = m.id','left')// 商家
        ->join($this->tbShop.' s','s.merchant_id=m.id') // 店铺
		->join($this->tbProduct.' p','p.id=co.product_id','left')//产品
		->join($this->tbOrder.' o','o.id=co.order_id','left');//订单
		return $this->pagination($this->tbComment.' co');
	}
	
	
}